<template>
    <tableLayout :columns="columns" :operationShow="false" :get="getData" :selectItem="selectItem" :rules="rules"
        ref="layout" :row-selection="selection">
        <template #button>
            <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
            <a-button type="primary" style="margin-left: 20px" @click='Test'>测试</a-button>
            <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="del" :disabled="selectedRowKeys.length !== 1"
                danger>删除</a-button>
        </template>

        <template #operationMore="item">
            <a @click="edit(null, item.value.record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="del(null, item.value.record.Id)">删除</a>
        </template>

        <template v-slot:custom="data">
            <a-input v-model:value="data.formData[data.key]" />
        </template>
    </tableLayout>

    <Modal ref="formModalRef" :title="editDefData.Id ? '编辑表单' : '新增表单'" @ok="addSubmit" @cancel="formRef.reset()"
        v-if="save">
        <Form ref="formRef" name="add" :formItem="formItem" :rules="rules" :setData="save" :additional="addToData"
            :defaultData="editDefData" @succeed="addComplete" @fail="formModalRef.loading(false)">
            <template v-slot:[formSlot(item)]="{ formData, key }" v-for="item in formItem">
                <slot :name="item.slotName" :formData="formData" :key="key" v-if="item.type === 'slot'" />
            </template>
        </Form>
    </Modal>

</template>


<script lang="ts" setup>
import { notification, message } from 'ant-design-vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { ref, UnwrapRef, reactive, nextTick, h } from 'vue';
import { useRoute } from 'vue-router';
import { getOnlineInfoByFormCode } from '@/api/online/online';
import { OnlineInput, DataForm, ApiConfigType } from '@/types/api/online/online';
import request from '../../request';
import { set } from 'store';
import Form from '@/components/tableLayout/form.vue'
import Modal from '@/components/tableLayout/modal.vue'
import { FormItem, SetData, GetData, EditData, OptionsData } from '@/components/tableLayout/type'
import { json } from 'stream/consumers';
import { filter } from 'lodash';
import { el } from 'element-plus/es/locale';

const context = defineEmits(['editOpen', 'addOpen', 'editSuccess', 'addSuccess']);
const layout = ref();
const formRef = ref()
const formModalRef = ref()
const formInfo = ref<any>({});
const formItem = ref<FormItem[]>([]);
// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const singleSelection = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
    selectedRowKeys.value = keys.splice(0, 1);
    selectedRows.value = rows.splice(0, 1);
    singleSelection.value = rows[0];
}
const selection = ref({});
//列表
const columns = ref<any[]>([]);

const selectItem = ref<any[]>([]);

const rules = reactive<any>({});

const editDefData: any = reactive({});

const addToData: any = ref<Record<string, any>>();
//取到url的参数

const route = useRoute();
const FormCode = route.query.FormCode;
// 用于存储动态注册的函数
const dynamicFunctions = ref<Record<string, Function>>({});

// 添加一个专门用于注册动态脚本的函数
const registerDynamicScript = (script: string) => {
    try {
        // 创建一个安全的执行上下文
        const scriptContext = {
            // 可以在这里注入需要的全局变量或工具函数
            message,
            request,
            // 提供一个注册函数的接口
            registerFunction: (name: string, func: Function) => {
                dynamicFunctions.value[name] = func;
            }
        };

        // 使用Function构造函数替代eval，更安全
        const scriptFunc = new Function('context', `
            with(context) {
                ${script}
            }
        `);

        scriptFunc(scriptContext);
    } catch (error) {
        console.error('动态脚本注册失败:', error);
        message.error('动态脚本注册失败!');
    }
}

// 添加一个调用动态函数的辅助方法
const callDynamicFunction = (name: string, ...args: any[]): any => {
    if (dynamicFunctions.value[name] && typeof dynamicFunctions.value[name] === 'function') {
        try {
            return dynamicFunctions.value[name](...args);
        } catch (error) {
            console.error(`调用动态函数${name}失败:`, error);
            message.error(`调用动态函数失败!`);
            return null;
        }
    } else {
        console.warn(`未找到动态函数: ${name}`);
        return null;
    }
}

const initOnlineInfoByFormCode = async () => {
    if (FormCode) {
        columns.value = [];
        getOnlineInfoByFormCode({ 'formCode': FormCode }).then(res => {
            var data = res.data.Data;
            formInfo.value = data;
            layout.value.getData({ 'param': null });
            if (data && data.Fields) {
                //遍历Fields
                data.Fields.forEach((field: any) => {
                    //给formState赋值
                    let column = { title: field.FieldCnName, dataIndex: field.FieldEnName };
                    columns.value.push(column);
                    if (field.IsSearch) {
                        selectItem.value.push({ title: field.FieldCnName, key: field.FieldEnName, type: 'input', itemWidth: '290px' });
                    }

                    if (field.IsRequired) {
                        rules[field.FieldEnName] = [{ required: true, message: `请输入${field.FieldCnName}`, trigger: 'change' }];
                    }

                    if (field.IsFormShow) {
                        let formType = 'input';
                        if (field.FieldType === 'int' || field.FieldType === 'float' || field.FieldType === 'double') {
                            formType = 'number';
                        }
                        else if (field.FieldType === 'text' || field.FieldType === 'ntext') {
                            formType = 'textarea';
                        }
                        else if (field.FieldType === 'datetime' || field.FieldType === 'date') {
                            formType = 'datePicker';
                        }
                        else if (field.FieldType === 'bit') {
                            formType = 'checkbox';
                        }
                        else if (field.FieldType === 'select') {
                            formType = 'select';
                        }
                        else if (field.FieldType === 'file' || field.FieldType === 'image') {
                            formType = 'upload';
                        } else if (field.FieldType === 'radio') {
                            formType = 'radio';
                        } else if (field.FieldType === 'checkbox') {
                            formType = 'checkbox';
                        } else if (field.FieldType === 'switch') {
                            formType = 'switch';
                        }

                        formItem.value.push({ title: field.FieldCnName, key: field.FieldEnName, type: formType });
                    }
                });

                if (data.IsShowCheckBox) {
                    selection.value = { selectedRowKeys: selectedRowKeys, onChange: onSelectChange };
                    if (data.IsSingleSelected) {
                        selection.value.type = 'radio';
                    } else {
                        selection.value.type = 'checkbox';
                    }
                }
            }

            columns.value.push({
                title: '操作',
                key: 'action',
                dataIndex: 'operation',
                slots: { customRender: 'operationMore' }
            });

            let apiConfigs = JSON.parse(data.ApiConfigs);
            apiConfigs = apiConfigs.filter((config: any) => config.type === ApiConfigType.custom);
            if (apiConfigs && apiConfigs.length > 0) {
                apiConfigs.forEach((config: any) => {
                    // debugger
                    // eval(config.script);
                    registerDynamicScript(config.script);
                });
            }

        }).catch(err => {
            console.log(err);
            message.error(err.message || "获取表单信息失败!")
        })
    }
}

const init = () => {
    initOnlineInfoByFormCode();
}



//如何在渲染前执行init
init();


// 表单
// const formItem = [
//     { title: '姓名', key: 'TableName', type: 'input' }, { title: '年龄', key: 'age', type: 'number' },
//     { title: '住址', key: 'addr', type: 'input' }, { title: '手机号', key: 'phone', type: 'input' },
//     { title: '行业', key: 'industry', type: 'input' }, {
//         title: '净资产', key: 'wealth', type: 'select',
//         options: [
//             { value: 10, label: '10亿' }, { value: 20, label: '20亿' },
//             { value: 30, label: '30亿' }, { value: 40, label: '40亿' },
//             { value: 999, label: '50亿+' }
//         ]
//     },
//     { title: '头像', key: 'avatar', type: 'upload' },
//     { title: '车型', key: 'cat', type: 'checkbox', options: [], optionKey: 'cat' },
//     { title: '备注', key: 'content', type: 'textarea', itemWidth: 'calc(100% - 20px)', labelCol: 3 },
//     { title: '表单插槽', key: 'formnet', type: 'slot', slotName: 'custom' },
// ]

//表单数据
const getData = (params: any) => {
    if (formInfo.value && formInfo.value.DataForm == DataForm.API) {
        params = { param: params };
        let apiConfigs = JSON.parse(formInfo.value.ApiConfigs);
        let apiConfig = apiConfigs.find((config: any) => config.type === ApiConfigType.get);
        //请求接口获取数据
        return request({
            url: apiConfig.url,
            method: apiConfig.method,
            params,
            headers: {
                'Content-Type': 'application/json'
            }
        })
    } else {
        return Promise.resolve({ data: { Data: [], Total: 0 } });
    }
}

const Test = () => {
    callDynamicFunction("Test1");
}

// 解析表单插槽名
const formSlot = (item: FormItem) => {
    return item.slotName ? item.slotName : 'noSlot'
}

const save = () => {

    //保存到服务器
    try {
        if (formInfo.value && formInfo.value.DataForm == DataForm.API) {
            let params = { param: JSON.stringify(formRef.value.formData) };
            let apiConfigs = JSON.parse(formInfo.value.ApiConfigs);
            let apiConfig = apiConfigs.find((config: any) => config.type === ApiConfigType.saveOrUpdate);

            if (!apiConfig.method) {
                apiConfig = apiConfigs.find((config: any) => config.type === ApiConfigType.add);
            }

            if (!apiConfig.method) {
                apiConfig = apiConfigs.find((config: any) => config.type === ApiConfigType.update);
            }

            //请求接口获取数据
            return request({
                url: apiConfig.url,
                method: apiConfig.method,
                params,
                headers: {
                    'Content-Type': 'application/json'
                }
            })

        } else {
            return Promise.resolve({ data: { Data: [], Total: 0 } });
        }
        layout.value.getData();
        selectedRowKeys.value = [];
    } catch (err: any) {
        message.error(err.message || "操作失败!")
    }
}

//新增
const add = () => {
    formModalRef.value.open();
    selection.value.selectedRowKeys = [];
    editDefData.value = {};
}

// 提交添加的数据
const addSubmit = () => {
    formModalRef.value.modalLoading = true
    formRef.value.onSubmit()
}

const edit = (event: any, item: any) => {
    let selectItem = item;
    if (!selectItem) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectItem = selectedRows.value[0];
    }
    Object.keys(selectItem).forEach(key => {
        editDefData[key] = selectItem[key]
    })

    formModalRef.value.open();
}

//删除一条记录
const del = (event: any, id: any) => {
    let selectId = id;
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectId = selectedRows.value[0].Id;
    }

    if (formInfo.value && formInfo.value.DataForm == DataForm.API) {
        let params = { param: JSON.stringify({ Id: selectId }) };
        let apiConfigs = JSON.parse(formInfo.value.ApiConfigs);
        let apiConfig = apiConfigs.find((config: any) => config.type === ApiConfigType.delete);
        //请求接口获取数据
        return request({
            url: apiConfig.url,
            method: apiConfig.method,
            params,
            headers: {
                'Content-Type': 'application/json'
            }
        })
    } else {
        return Promise.resolve({ data: { Data: [], Total: 0 } });
    }
}

/***********编辑数据***********/
const addForm = ref()
const addModal = ref()

// 表单添加提交完成回调
const addComplete = () => {
    addModal.value.close()
    addForm.value.reset()
    context.emit('addSuccess')
    //getData()
    //getOptions()
}



const labelCol = { span: 6 };
const wrapperCol = { span: 18 };
</script>

<style lang="scss" scoped>
.editable-row-operations {
    a {
        margin-right: 8px;
    }

    .disabled {
        a {
            color: #ccc;
            cursor: not-allowed;
        }
    }
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;

    }


    .ant-modal-body {
        flex: 1;
    }
}

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1 !important;
            flex-shrink: 0;
        }
    }
}
</style>
<style lang="scss">
.editable-row-operations a {
    margin-right: 8px;
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;

    }



    .ant-modal-body {
        flex: 1;
    }
}

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}
</style>